package com.atldy.commerce.config;

import feign.RequestInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.Optional;

/**
 * <h2> feign 调用时候要把Headed 也传递到服务提供方 </h2>
 *
 * @Author: li-dong-yang
 * @CreateTime: 2021-11-04 20:59
 */
@Slf4j
@Configuration
public class FeignConfig {

    /**
     * <p>feign 去配置请求拦截器</p>
     * RequestInterceptor 是我们提供给open feign的请求拦截器 把Headed信息进行传递
     */
    @Bean
    public RequestInterceptor headerRequestInter() {

        return template -> {
            ServletRequestAttributes attributes =
                    (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            Optional.ofNullable(attributes).ifPresent(requestAttributes -> {
                HttpServletRequest request = requestAttributes.getRequest();
                Enumeration<String> headerNames = request.getHeaderNames();
                Optional.ofNullable(headerNames).ifPresent(header -> {
                    while (header.hasMoreElements()) {
                        String name = header.nextElement();
                        String value = request.getHeader(name);
                        // 不能把当 前请求的content-length 传递到下游的服务提供方, 这明显是不对的
                        //请求可能一直返回不了，或者是请求响应数据被截断
                        if (!name.contains("content-length")) {
                            template.header(name, value);
                        }
                    }
                });
            });
        };
    }

}